package com.winchain.chainbill.tbill.biz.rx;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.file.service.PubFileService;
import com.shell.bee.invoince.po.InvBas;
import com.shell.bee.invoince.po.InvBasHist;
import com.shell.bee.invoince.po.InvUseStats;
import com.shell.bee.invoince.service.InvBasHistService;
import com.shell.bee.invoince.service.InvBasService;
import com.shell.bee.invoince.service.InvUseStatsService;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.winchain.chainbill.bill.base.dao.CbAttDao;
import com.winchain.chainbill.bill.base.po.CbAtt;
import com.winchain.chainbill.bill.base.service.CbAttService;
import com.winchain.chainbill.bill.biz.send.vo.BillAttInvoice;
import com.winchain.chainbill.tbill.base.po.TbDct;
import com.winchain.chainbill.tbill.base.po.TbRec;
import com.winchain.chainbill.tbill.biz.TBill;
import com.winchain.chainbill.tbill.biz.TBillEvent;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TBillSaveAttSubscriber extends OnErrorNotImplementedSubscriber<TBillEvent<TbDct>> {
	@Autowired
	private CbAttService cbAttService;
	@Autowired
	private InvUseStatsService invUseStatsService;
	@Autowired
	private InvBasHistService invBasHistService;
	@Autowired
	private InvBasService invBasService;
	@Autowired
	private CbAttDao cbAttDao;
	@Autowired
	private PubFileService pubFileService;

	public void onApplicationEvent(TBillEvent<TbDct> t) {
		try {
			String invType = "5";
			BigDecimal balanceBillAmt;
			TbRec tbRec = t.getBill().getRec();
			TbDct tbDct = (TbDct) t.getBill().getSource();
			String bizId = null;
			if (tbDct != null) {
				bizId = tbDct.getDctId();
			}
			BigDecimal billAmt = tbRec.getBillAmt();
			String contractFileIds = t.getStringValue("contractFileIds");
			String attInvoicesJson = t.getStringValue("attInvoicesJson");

			List<CbAtt> delCbAtts = this.cbAttDao.selectDelCbAtt(bizId, tbRec.getBillId(), "10", null);
			CbAtt delAtt;
			Iterator localIterator1;
			if ((delCbAtts != null) && (delCbAtts.size() > 0)) {
				for (localIterator1 = delCbAtts.iterator(); localIterator1.hasNext();) {
					delAtt = (CbAtt) localIterator1.next();
					this.cbAttDao.deleteByPrimaryKey(delAtt.getAttId());
					this.pubFileService.clearRelateId(delAtt.getAttId(), "10");
				}
			}
			List<CbAtt> cbAtts = this.cbAttDao.selectDelCbAtt(bizId, tbRec.getBillId(), "11", null);
			for (CbAtt cbAtt : cbAtts) {
				this.cbAttDao.deleteByPrimaryKey(cbAtt.getAttId());
				this.pubFileService.clearRelateId(cbAtt.getAttId(), "11");
				this.invBasService.deleteAndUpdateInv(cbAtt.getAttId(), invType);
			}
			Map<List<String>, List<BillAttInvoice>> map = this.cbAttService.saveCbAtt(tbRec.getBillId(), bizId,
					contractFileIds, attInvoicesJson, "10", "11");
			if ((!StringUtil.emptyAndNull(attInvoicesJson)) && (map != null) && (map.size() > 0)) {
				List<BillAttInvoice> savecbAtts = (List) map.values().iterator().next();
				if ((savecbAtts != null) && (savecbAtts.size() > 0)) {
					BigDecimal balance = BigDecimal.ZERO;
					BillAttInvoice attInvoice;
					StringBuilder histSb = new StringBuilder();
					for (Iterator localIterator2 = savecbAtts.iterator(); localIterator2.hasNext();) {
						attInvoice = (BillAttInvoice) localIterator2.next();
						InvUseStats invUseStats = this.invUseStatsService.selectOneByCodeAndNo(attInvoice.getInvCode(),
								attInvoice.getInvNo());
						if (invUseStats != null) {
							BigDecimal afterBalance = invUseStats.getInvAmt().subtract(invUseStats.getUseAmt());
							balance = balance.add(afterBalance);
							InvBasHist invBasHist = this.invBasHistService.selectOneByCodeAndNo(attInvoice.getInvCode(),
									attInvoice.getInvNo());
							if ((invBasHist != null) && (invBasHist.getState().equals("1"))) {
								histSb.append(attInvoice.getInvCode()).append(":").append(attInvoice.getInvNo())
										.append(",");
							}
						} else {
							BigDecimal invAmt = transferInvAmt(attInvoice.getInvAmt());
							balance = balance.add(invAmt);
						}
					}
					if (billAmt.compareTo(balance) > 0) {
						throw new UnCheckMsgException("������������������������������������������������");
					}
					if ((histSb != null) && (histSb.length() > 0)) {
						String histStr = histSb.substring(0, histSb.length() - 1);
						throw new UnCheckMsgException("��������" + histStr + "����������");
					}
					balanceBillAmt = billAmt;
					for (BillAttInvoice attInvoice2 : savecbAtts) {
						InvBas invBas = new InvBas();
						BeanUtils.copyProperties(attInvoice2, invBas);
						invBas.setInvAmt(transferInvAmt(attInvoice2.getInvAmt()));
						invBas.setTax(transferInvAmt(attInvoice2.getTax()));
						invBas.setTaxRate(transferTaxRate(attInvoice2.getTaxRate()));
						balanceBillAmt = this.invBasService.saveAndUpdateInvBasInfo(attInvoice2.getAttId(), invBas,
								invType, balanceBillAmt, CommonDataUtil.getUserId());
					}
				}
			}
		} catch (Exception e) {
			throw new UnCheckMsgException(e.getMessage());
		}
	}

	private BigDecimal transferInvAmt(String amt) {
		String ramt = amt;
		if (StringUtil.notEmpty(ramt)) {
			ramt = ramt.replace("��", "").replace("��", "").replace("$", "");
		}
		if (!StringUtil.emptyAndNull(ramt)) {
			return new BigDecimal(ramt.trim());
		}
		return null;
	}

	private BigDecimal transferTaxRate(String taxRate) {
		if ((StringUtil.notEmpty(taxRate)) && (taxRate.indexOf("%") >= 0)) {
			String rate = taxRate.replace("%", "").trim();
			if (StringUtil.emptyAndNull(rate)) {
				return null;
			}
			return new BigDecimal(rate).divide(new BigDecimal("100"), 2, 4);
		}
		if (StringUtil.notEmpty(taxRate)) {
			return new BigDecimal(taxRate.trim());
		}
		return null;
	}
}
